package com.felix.ocoupon.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

/**
 * <h1>通用抽象过滤器类</h1>
 * @author hsufelix
 * @email hsufelix@yeah.net
 * @Date 2020/11/10 19:45
 */
public abstract class AbstractZuulFilter extends ZuulFilter {

    /**
     * 用于过滤器中通信，当Map用吧
     * 数据会保存在每个请求的ThreadLocal中
     */
    RequestContext context;

    private final static String NEXT = "next";

    @Override
    public boolean shouldFilter() {
        final RequestContext ctx = RequestContext.getCurrentContext();
        return (Boolean) ctx.getOrDefault(NEXT, true);
    }

    @Override
    public Object run() throws ZuulException {
        context = RequestContext.getCurrentContext();
        return customizeRun();
    }

    protected abstract Object customizeRun();

    Object fail(int code, String msg) {
        context.set(NEXT, false);
        context.setSendZuulResponse(false);
        context.getResponse().setContentType("text/html;charset=UTF-8");
        context.setResponseStatusCode(code);
        context.setResponseBody(String.format("{\"result\": \" %s!\"}", msg));
        return null;
    }

    Object success() {
        context.set(NEXT, true);
        return null;
    }




}
